﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Reflection;
using Microsoft.WindowsMobile.Status;
using System.Threading;

namespace BluetoothManager
{
    public partial class frmMain : Form
    {
        string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase);

        Bitmap bluetoothOn;
        Bitmap bluetoothOff;

        public frmMain()
        {
            InitializeComponent();

            SystemState bluetoothStatePowerOn = new SystemState(SystemProperty.BluetoothStatePowerOn);
            bluetoothStatePowerOn.Changed += new ChangeEventHandler(bluetoothStatePowerOn_Changed);

            bluetoothOn = new Bitmap(Path.Combine(path, "bluetoothOn.png"));
            bluetoothOff = new Bitmap(Path.Combine(path, "bluetoothOff.png"));
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            ToggleMode();
        }

        void bluetoothStatePowerOn_Changed(object sender, ChangeEventArgs args)
        {
            UpdateScreen();
        }

        private void pictureBox_Click(object sender, EventArgs e)
        {
            ToggleMode();
        }

        private void ToggleMode()
        {
            if (BluetoothRadio.GetBluetoothRadioMode() == RadioMode.Off)
                BluetoothRadio.SetBluetoothRadioMode(RadioMode.Connectable);
            else
                BluetoothRadio.SetBluetoothRadioMode(RadioMode.Off);
        }

        private void UpdateScreen()
        {
            if (BluetoothRadio.GetBluetoothRadioMode() == RadioMode.Off)
            {
                textBox.Text += "Bluetooth radio is powered off." + Environment.NewLine;
                pictureBox.Image = bluetoothOff;
            }
            else
            {
                textBox.Text += "Bluetooth radio is powered on." + Environment.NewLine;
                pictureBox.Image = bluetoothOn;
            }
        }

        private void buttonOn_Click(object sender, EventArgs e)
        {
            BluetoothRadio.SetBluetoothRadioMode(RadioMode.Connectable);
        }

        private void buttonOff_Click(object sender, EventArgs e)
        {
            BluetoothRadio.SetBluetoothRadioMode(RadioMode.Off);
        }

        private void timer_Tick(object sender, EventArgs e)
        {
            textBox.Text = string.Empty;

            for (int i = 10; i > 0; i--)
            {
                textBox.Text += string.Format("Auto shutdown in {0} seconds..." + Environment.NewLine, i);
                Thread.Sleep(1000);
            }

            this.Close();
        }
    }
}